const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

function Promise(executor){
    let self = this;
    this.status = PENDING;
    this.value = undefined;
    this.reason = undefined;
    self.onFulfilled = [];
    self.onRejected = [];

    function resolve(value) {
        if(self.status === PENDING) {
            self.status = FULFILLED;
            self.value = value;
            self.onFulfilled.forEach(fn => fn());
        }
    }

    function reject(reason){
        if(self.status === PENDING) {
            self.status = REJECTED;
            self.reason = reason;
            self.onRejected.forEach(fn => fn());
        }
    }

    try {
        executor(resolve,reject);
    } catch(e) {
        reject(e);
    }
}

Promise.prototype.then = function(onFulfilled,onRejected) {
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
    onRejected = typeof onRejected === 'function' ? onRejected : reason => {throw reason};

    let self = this;
    let promise2 = new Promise((resolve, reject) => {
        if (self.status === FULFILLED) {
            queueMicrotask(() => {
                try {
                    let x = onFulfilled(self.value);
                    resolvePromise(promise2, x, resolve, reject);
                } catch(e) {
                    reject(e);
                }
            })
        } else if (self.status === REJECTED) {
            queueMicrotask(() => {
                try {
                    let x = onRejected(self.reason);
                    resolvePromise(promise2, x, resolve, reject);
                } catch (e) {
                    reject(e);
                } 
            })
        } else if (self.status === PENDING) {
            /** 把成功回调包裹成函数放入 onFulfilled 队列，等待状态变更时执行 */
            self.onFulfilled.push(() => {
                queueMicrotask(() => {
                    try {
                        let x = onFulfilled(self.value);
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        reject(e);
                    } 
                })
            })

            /** 把失败回调包裹成函数放入 onRejected 队列，等待状态变更时执行 */
            self.onRejected.push(()=> {
                queueMicrotask(() => {
                    try {
                        let x = onRejected(self.reason)
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        reject(e);
                    }
                })
            })
        }
    })
    return promise2;
}

/** 处理then回调返回值 */
function resolvePromise(promise, x, resolve, reject) {
    if (promise === x) {
        reject(new TypeError('Chaining cycle'));
    }
    if ((x && typeof x === 'object') || typeof x === 'function') {
        /** 用于标记是否使用过 resolve 或 reject，避免多次调用 */
        let used
        try {
            let then = x.then;
            if (typeof then === 'function') {
                /** 调用then方法，第一个参数：成功回调 第二个参数：失败回调 */
                then.call(
                    x,
                    y => {
                        if (used) return;
                        used = true;
                        resolvePromise(promise, y, resolve, reject);
                    },
                    r => {
                        if (used) return;
                        used = true;
                        reject(r)
                    }
                )
            } else {
                /** then不是函数，说明x是普通对象 */
                if (used) return;
                used = true;
                resolve(x);
            }
        } catch (e) {
            if (used) return;
            used = true;
            reject(e);
        }
    } else {
        /** x不是对象或函数，直接resolve */
        resolve(x);
    }
}

/** defer:将Promise的创建和它的完成(resolve 和 reject)解耦开 */
Promise.defer = function() {
    let result = {};
    result.promise = new Promise((resolve, reject) => {
        result.resolve = resolve;
        result.reject = reject;
    })
    return result;
}

module.exports = Promise;